var cssshine;
var orderTimerInterval = 1000*60*5;
var messageflag = false;
window.onblur = function () {
    messageflag=true;
}
window.onfocus = function () {
    messageflag=false;
}
$(function ($) {
    $.extend({
        ordercss: function (data) {
            if(data && data.uapOrderVO){
                //未处理订单
                $(".order-task .module-content .data:eq(0) span").html(data.uapOrderVO.currentWaitOrderNumber);
                //今日处理订单
                $(".order-task .module-content .data:eq(1) p").html(data.uapOrderVO.currentNumber);

                //清空历史记录
                $(".order-task .module-content .data_parent-border").remove();

                var $orderList = $('<div class="data_parent-border" >' +
                    '<div class="data_border_box data_border_box_task" >' +
                    '<table class="data-table task_table">' +
                    '<tbody></tbody>' +
                    '</table>' +
                    '</div>' +
                    '</div>');

                if(data.uapOrderVO.uapOrders.length > 0){
                    $.each(data.uapOrderVO.uapOrders,function(index,item){
                        //日期处理
                        var createDate = new Date(item.createTime);
                        var time = createDate.format("yyyy-MM-dd hh:mm");
                        //当前状态处理
                        var status = new Date(createDate.getTime() + 1000 * 60 * 10) > new Date(data.currentTime) ? '<td><label class="label label-default normal_default table_label">正常</label></td>':'<td><label class="label label-danger table_label">紧急</label></td>';

                        var $info = $(orderInfoHtml.replace("{serialNumber}",index+1).replace("{orderNumber}",item.orderNumber).replace("{createTime}",time).replace("{status}",status));
                        $info.find("td div.orderNumber").attr('title',item.orderNumber);
                        //绑定 访问首页页面
                        $info.find("td button.table_button").click(function(){
                            var href = OMS_SERVER_NAME +'oms-ltl-web/uaporder/uaporder.action?orderNumber=' + item.orderNumber;
                            var viewType = "DIV";
                            var tab = getTabById(href,viewType);
                            if( tab ){
                                closeTab(href,viewType);

                            }

                            viewTab('订单处理',href,viewType);
                        });

                        $orderList.find("table tbody").append($info);
                    });

                    $(".order-task .module-content").append($orderList);
                    workOrderTask();
                }else {
                    workOrderTaskOrderTaskisNull();
                }
            }else{
                workOrderTaskOrderTaskisNull();
            }

        }
    });
    $.extend({
        supercss: function (res) {
            res = res[0];
            var lis = "<li class='cssappend'><a  class='dropdown-toggle' data-toggle='dropdown' aria-expanded='false' href='javascript:return false;' ><i class='fa fa-envelope-o'></i><span onclick=\"viewTab(\'" + res.mesName + "\',\'" + res.linkUrl + "\',\'IFRAME\')\"  class='label label-success'>" + res.msgNumber + "</span>";
            $("#navMain").prepend(lis);
        }
    });
    $.extend({
        smallcss: function (res,str) {
            var lis = "";
            var oms1009 = "";
            var cssshake = false;
            $(res.childNodes).each(
                function (j, f) {
                    var connum = f.msgNumber;
                    var mesTitleName = queryMesTitle(f.mesCode);
                    if(''==mesTitleName){
                        mesTitleName = f.mesName ;
                    }
                    if(connum>0 && 'undefined'!=connum){
                        var umcslinkurl = f.linkUrl
                        var searchcss = '';
                        var paramumcs = 'DIV';
                        if(umcslinkurl.indexOf('?')!=-1){
                            var pairs=umcslinkurl.split('?');
                            searchcss = pairs[1]
                            paramumcs = getUrlParam(searchcss,"isdori");
                        }
                        if(paramumcs=='IFRAME'||'iframe'==paramumcs){
                            paramumcs = 'IFRAME';
                        }

                        if(f.mesCode == '1001'||f.mesCode == '1002'||f.mesCode == '1003'||f.mesCode == '1004'||f.mesCode == '1005'||f.mesCode == '2001'||f.mesCode == '2002'||f.mesCode == '2003'){
                        		
                        }else{
                            lis += "<li class=\'"+f.mesCode+"\'><p onclick=\"viewTab(\'" + mesTitleName + "\',\'" + f.linkUrl + "\',\'"+paramumcs+"\')\">"+f.mesName+"</p><span>"+f.msgNumber+"</span></li>";
                        }
                        

                        //lisonedb = "<li class=\'"+f.mesCode+"\'><p onclick=\"viewTab(\'" + mesTitleName + "\',\'" + f.linkUrl + "\',\'"+paramumcs+"\')\">"+f.mesName+"</p><span>"+f.msgNumber+"</span></li>";

                    }

                });

            return lis;
        }
    });
    $.extend({
        bigcss: function (rs,strygdsb) {
            var dblength = $(".messages-menu-xx li").length;

            for (var i = 0; i < dblength; i++) {
            	if($(".messages-menu-xx li")==undefined ||$(".messages-menu-xx li")=='' ){
            		
            	}else{
                    if($(".messages-menu-xx li")[i] != undefined){
                        var dbcontent = $(".messages-menu-xx li")[i].className;
                        if (dbcontent != "1008") {
                            $(".messages-menu-xx li")[i].remove();

                        }
                    }
            	}
            	
                
            }

            $(".db-menu-db li").remove();
            // $("#messages-count").text("0");
            // $("#task-count").text("0");
            $(rs).each(function (i, d) {
                if (null!=d.childNodes&&d.childNodes.length > 0) {
                    var typemes = d.mesCode;
                    if (1 == typemes) {
                        var topiftools = $('.1008');

                        var omsddslnum ;
                        var omsxycount ;

                        if(undefined == topiftools){

                        }else{

                            omsddslnum = topiftools[0];
                            omsxycount = 0;
                            if(undefined == omsddslnum){
                                omsxycount = 0 ;
                            }else{
                                omsxycount = omsddslnum.children[1].textContent;
                            }
                        }

                        var countcss = parseInt(d.msgNumber)+parseInt(omsxycount) ;

                    }
                    if (2 == typemes) {
                        $(".need-read .tasks-menu-header").html("<div>您有" + "<span></span>" + "未读消息</div>");
                    }
                    //待办一 消息二   （原先消息一  待办二在5月份umc系统改了后现在用新的JS不处理，周知）   aria-expanded="false"
                    if (2 == typemes) {
                        $(".db-menu-db").append($.smallcss(d,2))
                    }

                    if (1 == typemes) {
                        var dbstrss = $.smallcss(d,1);
                        if(dbstrss.length>0){
                        	if(strygdsb == 'vb'){
                        		//$(".need-to-do").removeClass("open");
                        	}else{
                        		$(".need-to-do").removeClass("open");
                        	}
                            
                            $(".messages-menu-xx").append(dbstrss);
                        }

                    }
                    var sumomsnum = sumTotalDBnum();
                    $(".need-to-do .messages-menu-header").html("<div>您有" + "<span></span>" + "新待办任务</div>");


                }else{
                    if(undefined != d){
                        if(d.mesCode =='1' ){
                            var dblength = $(".messages-menu-xx li").length;
                            for (var i = 0; i < dblength; i++) {
                                var dbcontent = $(".messages-menu-xx li")[i].className;

                                if (dbcontent != "1008") {
                                    $(".messages-menu-xx li")[i].remove();
                                }
                            }

                        }
                    }

                    $(".need-to-do .messages-menu-header").html("<div>您有" + "<span></span>" + "新待办任务</div>");

                }
            })

        }
    });

    // queryTreeMes();

    $('.messages-menu .dropdown-toggle').click(function(){
    	var  flaggoorno = $(this).context.nextElementSibling;
    	
    	if(null != flaggoorno){
    		
    		$discontentflag = $(this).context.nextElementSibling.children[1].childElementCount;
        	
            if($discontentflag == 0 || parseInt($discontentflag) == 0 ){
            	
                $(this).next('.dropdown-menu').css({
                    'display':'none'
                });
            }else{
            	$(this).next('.dropdown-menu').css({
                    'display':''
                });
            }
    	}
    	
    	
    });
    
//    $('.need-refresh .fa').click(function(){
//    	refreshDSBYG();
//    });
    
    $('.need-to-do .fa').click(function(){
    	$flagdsbyg = $(".need-to-do .dbalertexpand").attr("aria-expanded");
    	
    	if($flagdsbyg){
    		// queryTreeMes();
    		
    	}else{
    		
    		$(".messages-menu-xx li").remove();
    	}
    	
    	
    	
  	});
    
    
    $('.need-read .fa').click(function(){
    	
    	$flagdsbygb = $(".need-read .dropdown-toggle").attr("aria-expanded");
    	
    	if($flagdsbygb){
    		// queryTreeMes();
    		
    	}else{
    		
    		$(".db-menu-db li").remove();
    	}
  	});
    
    

});

jQuery.fn.shake = function(cssNum, cssMove, cssTime) {
    this.each(function () {
        var cssShake = $(this);
        cssShake.css({ position: 'relative' });
        for (var x = 1; x <= cssNum; x++) {
            cssShake.animate({ left: (cssMove * -1) }, (((cssTime / cssNum) / 4)))
                .animate({ left: cssMove }, ((cssTime / cssNum) / 2))
                .animate({ left: 0 }, (((cssTime / cssNum) / 4)));
        }
    });
    return this;
}

function sumTotalDBnum(){
    var totalnum = 0;

    var dblength = $(".messages-menu-xx li").length;

    for (var i = 0; i < dblength; i++) {

        var nownum = $(".messages-menu-xx li")[i].childNodes[1].textContent;
        if(nownum == undefined ||nownum < 1||'' == nownum){

        }else{
            totalnum =  totalnum+parseInt(nownum);
        }


    }

    return totalnum;
}

function refreshDBXX(){
    //原先内容开始
    $(".messages-menu-xx li").remove();
    $(".db-menu-db li").remove();
    $("#messages-count").text("0");
    $("#task-count").text("0");

}

// function queryTreeMes(){
	
//     $.post(MESSAGE_SERVICE_URL + "treeMessageController/queryTreeMessage", {key: "1"}, function (rs) {
//         $('.messages-menu-xx .1008').remove();

//         $(".need-to-do .messages-menu-header").html("<div>您有" + "<span></span>" + "新待办任务</div>");
//         $(".need-read .messages-menu-header").html("<div>您有" + "<span></span>" + "新消息任务</div>");
//         queryFossMsg(rs);
        
        
        
//         setTimeout("refreshRedPoint()",800);

//     }, "json");
// }


var uapbeforetimesb;

function refreshSBYG(str){
	console.log(str);
	$('.need-refresh .fa').html(str);
}

function css_timems(timea,timeb){
    var csstime = 11;
    if(timea != undefined){
        csstime = Math.abs(parseInt((timeb - timea)/1000));
    }
    return csstime
}



function refreshDSBYG(){

    var uapthistime = new Date();

    var uapbooltime = css_timems(uapbeforetimesb,uapthistime);

    if(uapbooltime>10){
        uapbeforetimesb = uapthistime;
        $('.need-refresh .message-tip').hide();
        $('.need-refresh .message-tip-up').show();
        refreshDDSBYG();
    }else{
        console.log("消息代办手动刷新10秒间不能连续触发~");
    }
}


function refreshDDSBYG() {  
    var wait = $(".need-refresh .fa").html();  
    if(""==wait){
    	wait = 5;
    }
    
    
    
    timeOut();  
    /**  
     * 实现倒计时  
     */  
    function timeOut() {  
        if(wait != 0) {  
            setTimeout(function() { 
            	$discontent = --wait;
            	$discontentsbyg = $discontent - 1;
            	if($discontent==1){
            		// queryTreeMes();
            		$('.need-refresh .message-tip-up').html("刷新成功");
            		$('.need-refresh .fa').text("OK");
            		
            	}
            	else if($discontent==0){
            		$('.need-refresh .message-tip-up').html("正在刷新").hide();
            		$('.need-refresh .fa').text("");
            	}else{
            		$('.need-refresh .fa').text($discontentsbyg);
            	}
                timeOut();  
            }, 1000);  
        }  
    }  
};  

function refreshFossMsg(){
	$(".messages-menu-xx li").remove();
	$(".db-menu-db li").remove();
}

function refreshRedPoint(){
	
	$xxRedPoint = $(".need-to-do .messages-menu-xx")[0].childElementCount;
	$dbRedPoint = $(".need-read .db-menu-db")[0].childElementCount;
	if($xxRedPoint == 0 || parseInt($xxRedPoint) == 0 ){
		$('.need-to-do .message-reminding').hide();
    }else{
    	$('.need-to-do .message-reminding').show();
    }
	
	if($dbRedPoint == 0 || parseInt($dbRedPoint) == 0 ){
		$('.need-read .message-reminding').hide();
    }else{
    	$('.need-read .message-reminding').show();
    }
	
	
}


//

function queryFossMsg(rs){
    $.ajax({
        type:"POST",
        url:FOSS_SERVER_NAME + "bse-baseinfo-web/common/queryMsgTotal.action",
        dataType:"json",
        global:false,
        success:function(result){
        	refreshFossMsg();
        	
        	// queryThisTimeOmsOrder(1);
            $.bigcss(rs,"vb");
            if(result ){
            	var msgVo = result.msgVo;
            	        	
	            	if(msgVo != null ){    
		            	var netMsgList = msgVo.netMsgList;
		            	
		            	if (netMsgList == null || netMsgList.length == 0 || netMsgList[0].noDealNum == 0) {
		            		  //cleanMsg("受理在线通知");
		                  } else {//受理在线通知
		                	  buildMsg("在线通知",FOSS_SERVER_NAME+"bse-querying-web/querying/acceptNetMsgOnline.action",netMsgList[0].noDealNum);
		                  }
		            	
		            	
		            	var toDoMsgList = msgVo.toDoMsgList;
		            	
		            	if (toDoMsgList == null || toDoMsgList.length == 0) {
		            		
//		            		cleanMsg("处理待办");
//		            		cleanMsg("转寄退回件工单");
//		            		cleanMsg("快递更改单受理");
//		            		cleanMsg("悟空-管理营业部出发运单");
		            		
		                  } else {
		                	  
		                	  for ( var int = 0; int < toDoMsgList.length; int++) {
		                		  var businessType = toDoMsgList[int].businessType;
		
								if("PKP_WB_LAB_PT"==businessType){//更改单标签重打 处理待办
				                	  buildMsg("更改单标签重打",FOSS_SERVER_NAME+"pkp-deliver-web/waybill/todoActionIndex.action",toDoMsgList[int].noDealNum);
								}
								
								if("RETURN_GOODS_TODO"==businessType){
				                	  buildMsg("转寄退回件工单",ECS_SERVER_NAME+"tak-business-web/waybill/returnGoodsIndex.action?isUap=true",toDoMsgList[int].noDealNum);
								}
								
								if("PKP_WB_ACCECPT_WAY"==businessType){
				                	  buildMsg("快递更改单受理",ECS_SERVER_NAME+"tak-business-web/waybill/expBillChangeSel.action?isUap=true",toDoMsgList[int].noDealNum);
								}
								
								if("ECS_PDA_WAYBILL"==businessType){//悟空-管理营业部出发运单
				                	  buildMsg("快递待补录运单",ECS_SERVER_NAME+"tak-business-web/waybill/queryWaybill.action?isUap=true",toDoMsgList[int].noDealNum);
								}
								
								
								
							}
		                	  
		                  }
		            	
		            	
		            	
		            	var normalMsgList = result.msgVo.normalMsgList;
		                
		            	
		            	if (normalMsgList == null || normalMsgList.length == 0 || normalMsgList[0].noDealNum == 0) {
		          		  //cleanMsg("供应商补录失败消息");
		          		  //cleanMsg("站内消息");
		
		                } else {
		                	
		                	for ( var int = 0; int < normalMsgList.length; int++) {
		              		  var msgType = normalMsgList[int].msgType;
		
								if("SUPPLIER_FAIL_PATCH"==msgType){
				                	  buildMsg("供应商补录失败消息",FOSS_SERVER_NAME+"bse-baseinfo-web/common/instationMsgInit.action",normalMsgList[int].noDealNum);
								}
								
								if("NORMAL"==msgType){
				                	  buildMsg("普通消息",FOSS_SERVER_NAME+"bse-baseinfo-web/common/instationMsgInit.action",normalMsgList[int].noDealNum);
								}
								
							}
		
		                	
		                }
		            	
		            	
//		                var noDealTotal = msgVo.noDealtotal;
//		                var collectionMsgList = msgVo.collectionMsgList;
//		                var autoAbandMsgList = msgVo.autoAbandMsgList;
//		                var callCenterWaybillMsgList = msgVo.callCenterWaybillMsgList;
//		                var noDealTotal = msgVo.noDealtotal;
//		                var collectionMsgList = msgVo.collectionMsgList;
//		                var failingInvoiceMsgList = msgVo.failingInvoiceMsgList;
//		                var unReconciliationMsgList = msgVo.unReconciliationMsgList;
//		                var noRepaymentMsgList = msgVo.noRepaymentMsgList;
//		                var debitWillOverList = msgVo.debitWillOverList;
//		                var deliveryReturnList = msgVo.deliveryReturnList;
	            }else{

	            }
               
            }else{
                console.log("FOSS权限不足");
            }
        },
        error:function (res,state) {
            console.log("FOSS调用失败");

        }
    });
}

function buildMsg(title,url,number){
    if(title == '供应商补录失败消息'){
        var buildMsgStr = "<li class=\'"+title+"\'><p onclick=\"viewTab(\'"+"站内消息"+"\',\'" + url + "\','DIV')\">"+title+"</p><span>"+number+"</span></li>";
    	$(".db-menu-db").append(buildMsgStr)
    }else if(title == '普通消息'){
    	var buildMsgStr = "<li class=\'"+title+"\'><p onclick=\"viewTab(\'"+"站内消息"+"\',\'" + url + "\','DIV')\">"+title+"</p><span>"+number+"</span></li>";
    	$(".db-menu-db").append(buildMsgStr)
    }else if(title == '快递待补录运单'){
    	var buildMsgStr = "<li class=\'"+title+"\'><p onclick=\"viewTab(\'"+"悟空-管理营业部出发运单"+"\',\'" + url + "\','DIV')\">"+title+"</p><span>"+number+"</span></li>";
    	$(".messages-menu-xx").append(buildMsgStr);
    }else if(title == '在线通知'){
    	var buildMsgStr = "<li class=\'"+title+"\'><p onclick=\"viewTab(\'"+"受理在线通知"+"\',\'" + url + "\','DIV')\">"+title+"</p><span>"+number+"</span></li>";
    	$(".messages-menu-xx").append(buildMsgStr);
    }else if(title == '更改单标签重打'){
    	var buildMsgStr = "<li class=\'"+title+"\'><p onclick=\"viewTab(\'"+"代办事项"+"\',\'" + url + "\','DIV')\">"+title+"</p><span>"+number+"</span></li>";
    	$(".messages-menu-xx").append(buildMsgStr);
    }else{
    	var buildMsgStr = "<li class=\'"+title+"\'><p onclick=\"viewTab(\'"+title+"\',\'" + url + "\','DIV')\">"+title+"</p><span>"+number+"</span></li>";
    	$(".messages-menu-xx").append(buildMsgStr);
    }

    
    
}


function cleanMsg(title){
	
	$(".messages-menu-xx ."+title).remove();
}

function cleanMsgALL(){
	$(".messages-menu-xx li").remove();
	$(".db-menu-db li").remove();

}





// function queryThisTimeOmsOrder(str){
//     $.ajax({
//         type:"POST",
//         url:OMS_SERVER_NAME + "oms-ltl-web/uaporder/queryOrder.action",
//         data: {"uapOrderVO.uapOrderCondition.deptCode":userInfo.deptCode},
//         dataType:"json",
//         success:function(data){

//             $(".need-to-do").removeClass("open-always");
//             //open-always
//             if(data && data.uapOrderVO){
//                 if(str==1){

//                     var omsnum = data.uapOrderVO.currentWaitOrderNumber;

//                     if(omsnum>0){

//                         $(".need-to-do").addClass("open-always");

//                         var omsUrl = OMS_SERVER_NAME + 'oms-ltl-web/orderaccepted/accepted.action';
//                         var contentfianl = "<li class=\'"+"1008"+"\'><p style=\"color: red;\" onclick=\"viewTab('零担订单受理',\'" + omsUrl + "\','DIV')\">"+"零担订单待受理"+"</p><span style=\"color: red;\">"+omsnum+"</span></li>";

//                         $(".messages-menu-xx").prepend(contentfianl);

//                         if(document.hidden || messageflag) {
//                             orderWebNotification(omsnum,'零担订单受理',omsUrl,'DIV');
//                         };

//                     }else{
//                         $(".need-to-do").removeClass("open-always");
//                         $('.messages-menu-xx .1008').remove();
//                         var sumomsnum = sumTotalDBnum();
//                         $("#messages-count").text(controlLengthrep(sumomsnum,2));
//                         $(".need-to-do .messages-menu-header").html("<div>您有" + "<span></span>" + "新待办任务</div>");
//                     }
//                 }
//                 if(str==2){
//                     if(omsnum>0){
//                         $(".need-to-do").addClass("open-always");
//                     }else{
//                         $(".need-to-do").removeClass("open-always");
//                     }
//                 }

//             }else{
//                 console.log("oms权限不足");
//             }
//         },
//         error:function () {
//             console.log("oms调用失败");

//         }
//     });
// }

$(function () {
    setInterval("queryTreeMes()",orderTimerInterval);   
    // hoverMessage();
});

function refreshMesOMS(num,omsUrl){
    $(".need-to-do").removeClass("open-always");
    omsUrl = OMS_SERVER_NAME + 'oms-ltl-web/orderaccepted/accepted.action';

    $('.messages-menu-xx .1008').remove();

    // queryThisTimeOmsOrder(1);

}


function queryMesTitle(str){
    var strmes="";  //,"","","","","","",""
    var messtr = ["1001","1002","1003","1004","1005","1007","1008","2001","2005","1006","1012","1013","2002","1016","1017"];
    var mesnamestr=["受理在线通知","处理待办事项","转寄退回件工单","快递更改单受理","悟空-管理营业部出发运单","待办事项","零担订单受理","站内消息","订单站内消息","差错查询","待办事项","待办事项","站内消息","站内消息","站内消息"];
    for (var i = 0; i < messtr.length; i++) {
        if (messtr[i] == str) {
            strmes=mesnamestr[i];
            break;
        }
    }
    return strmes;
}





function getUrlParam(url,name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); 
    var r = url.match(reg);  
    if (r != null) return unescape(r[2]); return 'DIV';
}


function orderWebNotification(omsnum,NotifiName,omsUrl,type) {
    if (window.Notification) {
        if (Notification.permission == "granted") {
            var notification = new Notification("新到代办任务", {
                body: '您有'+omsnum+'条零担订单任务待受理',
                icon: UAP_SERVER_NAME +'resources/img/order_message_logo.gif',
                tag:10
            });
            notification.onclick = function() {
                viewTab(NotifiName,omsUrl,type);
                notification.close();
                window.focus();
            };
        }else {
            window.Notification.requestPermission(function (permission) {
                if (permission === "granted") {
                    var notification = new Notification("新到代办任务", {
                        body: '您有'+omsnum+'条零担订单任务待受理',
                        icon: UAP_SERVER_NAME +'resources/img/order_message_logo.gif',
                        tag:10
                    });
                }
            });
        }

    }else {
        alert('浏览器不支持Notification');
    }

}

// function hoverMessage() {
//     $('.messages-menu a').hover(
//         function () {
//             if($(this).next().css('display')=='block'){
//                 $(this).find('.message-tip').hide();
//             }else{
//                 $(this).find('.message-tip').show();
//             }
//         },function () {
//             $(this).find('.message-tip').hide();
//         }
//     )
// }
function closeMessageLead() {
   $(".lead-img").hide();
}